package cn.edu.stu.manager.factory;

import cn.edu.stu.bean.MicRecord;
import cn.edu.stu.bean.MicSong;
import cn.edu.stu.mapper.MicRecordMapper;
import cn.edu.stu.mapper.MicSongMapper;
import cn.edu.stu.service.ConfService;
import cn.edu.stu.service.RecordService;
import cn.edu.stu.tool.MD5Util;
import cn.edu.stu.tool.SpringUtils;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;
import java.util.TimerTask;

/**
 * @author Karl
 * @Date 2022/12/16 - 20:45
 */
public class AsyncFactory {

    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 提取并检验记录音乐信息
     *
     * @param filename 文件路径及名字
     * @return
     */
    /*
    public static TimerTask getAndCheckSongAttr(final String filename, MicSong song) {
        return new TimerTask() {
            @Override
            public void run() {
                File sourceFile = new File(filename);
                boolean flag = true;
                String md5 = MD5Util.getMd5ByFile(sourceFile);
                song.setSongMd5(md5);

                try {
                    MP3File mp3file = new MP3File(sourceFile);
                    //获取该音乐文件的属性标签
                    AbstractID3v2Tag tag = mp3file.getID3v2Tag();
                    //默认的图片及其未知
                    String imgPath ="0";
                    if (tag != null) {
                        try {
                            Object frame = tag.getFrame("APIC");
                            if (frame instanceof AbstractID3v2Frame) {
                                FrameBodyAPIC body = (FrameBodyAPIC) ((AbstractID3v2Frame) frame).getBody();
                                byte[] imageData = body.getImageData();
                                String uuid = UUIDUtil.getUUID();
//                                imgPath = sourceFile.getParent()+'\\'+uuid +".jpg";
                                File file = new File("img" + File.separator + uuid + ".jpg");
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(imageData);
                                fos.close();
                                imgPath = uuid;
                            }
                        } catch (IOException ioe){
                            imgPath = "0";
                        }

                        //获取标题
                        Object temp = mp3file.getID3v2Tag().frameMap.get("TIT2");
                        if (temp instanceof ID3v23Frame) {
                            String songName = ((ID3v23Frame) temp).getBody().getUserFriendlyValue();
                            if (songName != null) {
                                if (song.getSongName() != null) {
                                    song.setAlias(songName);
                                } else {
                                    song.setSongName(songName);
                                }
                            }
                        }

                        //获取作者名字
                        temp = mp3file.getID3v2Tag().frameMap.get("TPE1");
                        if (temp instanceof ID3v23Frame) {
                            String artist = ((ID3v23Frame) temp).getBody().getUserFriendlyValue();
                            if (song.getAuthorId() == null) {
                                // 没有作者读取并插入插入数据
                                int i = SpringUtils.getBean(ArtistService.class).checkOrInsertArtistId(artist);
                                song.setAuthorId(i);
                            }
                        }


                    }else{
                        if(song.getSongName()==null) song.setSongName("未知");
                        if(song.getAuthorId()==null||song.getAuthorId()==0) song.setAuthorId(1);
                    }
                    song.setImgPath(imgPath);

                    //获取歌曲时长
                    AudioHeader header = mp3file.getAudioHeader();
                    int duration = header.getTrackLength();
                    song.setDuration(duration*1000);



                } catch (Exception e) {
                    flag = false;
                    SpringUtils.getBean(MicSongMapper.class).deleteByPrimaryKey(song.getSongId());
                }
                if(flag) SpringUtils.getBean(MicSongMapper.class).updateByPrimaryKey(song);
            }
        };
    }
    */

    /**
     * 创建异步任务去读取mp3文件的音频长度
     * @param filename 音频文件所在地，决定路径
     * @param song  对应的song对象
     * @param record 对应的record记录，如果不是音频文件，把他删了
     * @return 异步任务
     */
    public static TimerTask getAndCheckSongAttr(final String filename, MicSong song, MicRecord record) {
        return new TimerTask() {
            @Override
            public void run() {
                File sourceFile = new File(filename);
                String md5 = MD5Util.getMd5ByFile(sourceFile);
                song.setSongMd5(md5);
                try {
                    MP3File mp3file = new MP3File(sourceFile);
                    //获取歌曲时长
                    AudioHeader header = mp3file.getAudioHeader();
                    int duration = 0;
                    if (header instanceof MP3AudioHeader){
                        duration = (int) (((MP3AudioHeader) header).getPreciseTrackLength()*1000);
                    }else{
                        duration = header.getTrackLength()*1000;
                    }

                    song.setDuration(duration);

                    //避免用户不使用checkUpload接口直接重复上传
                    List<MicSong> songs = SpringUtils.getBean(MicSongMapper.class).selectByMD5(md5);
                    if(songs.size()==1){
                        MicSong existSong = songs.get(0);
                        if (song.getSongMd5().equals(existSong.getSongMd5())&& song.getSongSize().equals(existSong.getSongSize())) {
                            //如果MD5相同并且文件大小相同，基本确定为同一文件
                            //删除并修改文件
                            SpringUtils.getBean(RecordService.class).updateSongId(song,existSong,record);
                            if (!sourceFile.delete()) {
                                System.out.println(sourceFile.getName()+"删除失败！");
                            }
                        }
                    }else{
                        SpringUtils.getBean(MicSongMapper.class).updateByPrimaryKey(song);
                    }
                } catch (Exception e) {
                    //说明不是一个mp3,用户骗我，将记录和文件删除
                    if (!sourceFile.delete()) {
                        System.out.println("不是MP3文件时删除"+sourceFile.getName()+"失败！");
                    }
                    SpringUtils.getBean(MicSongMapper.class).deleteByPrimaryKey(song.getSongId());
                    SpringUtils.getBean(MicRecordMapper.class).deleteByPrimaryKey(record.getRecordId());

                }
            }
        };
    }

    public static TimerTask checkDeleteSongFile(Integer songId) {
        return new TimerTask() {
            @Override
            public void run() {
                int cnt  = SpringUtils.getBean(MicRecordMapper.class).countBySongId(songId);
                if(cnt==0){
                    ConfService confService = SpringUtils.getBean(ConfService.class);
                    String filePath = confService.getRootPath() + confService.getFilePath() + songId + ".mp3";
                    File file = new File(filePath);
                    if(file.exists()){
                        if (!file.delete()) {
                            //启动异步任务去记录日志
                            System.out.println("delete mp3 file :" + songId +",mp3 fail!");
                        }
                    }
                }
            }
        };
    }

    public static TimerTask deleteSongImg(String imgPath) {
        return new TimerTask() {
            @Override
            public void run() {
                ConfService confService = SpringUtils.getBean(ConfService.class);
                String filePath = confService.getRootPath() + confService.getFilePath() + imgPath;
                File file = new File(filePath);
                if(file.exists()){
                    if (!file.delete()) {
                        //启动异步任务去记录日志
                        System.out.println("delete img file :" + imgPath +" fail");
                    }
                }
            }
        };
    }
}
